import re

class ATCommandParser:
    """AT指令解析器类，负责解析各种MQTT相关的AT指令"""
    
    def __init__(self):
        pass
    
    def parse_mqtt_command(self, command_str, command_type=None):
        """智能解析MQTT相关AT指令，提取参数并生成模板
        
        支持解析以下格式的AT指令：
        - 连接: AT+ECMTOPEN=0,"test.mosquitto.org",1883
        - 订阅: AT+ECMTSUB=0,1,"/lierda/test",2
        - 发布: AT+ECMTPUB=0,0,0,0,"/lierda/test","{\"vbat\":3700}"
        - 断开: AT+ECMTDISC=0
        - 认证: AT+ECMTCONN=0,"zackii","zack","123456"
        
        Args:
            command_str (str): 实际的AT指令字符串
            command_type (str, optional): 指令类型 ('connect', 'subscribe', 'publish', 'disconnect', 'conn')
                                        如果未指定，将尝试自动识别
        
        Returns:
            dict: 包含解析结果的字典，失败返回None
            返回格式：
            {
                "template": "AT+ECMTOPEN=0,{host_name},{port}",
                "original": "AT+ECMTOPEN=0,\"test.mosquitto.org\",1883",
                "broker": "test.mosquitto.org",
                "port": 1883,
                "client_id": "0",
                "parameters": {
                    "host_name": "test.mosquitto.org",
                    "port": 1883
                }
            }
        """
        try:
            command_str = command_str.strip()
            
            # 统一处理，移除末尾的\r\n
            command_str = command_str.rstrip('\r\n')
            
            # 如果未指定command_type，尝试从命令字符串中识别
            if command_type is None:
                if 'ECMTOPEN' in command_str.upper():
                    command_type = 'connect'
                elif 'ECMTSUB' in command_str.upper():
                    command_type = 'subscribe'
                elif 'ECMTPUB' in command_str.upper():
                    command_type = 'publish'
                elif 'ECMTDISC' in command_str.upper() or 'ECMTCLOSE' in command_str.upper():
                    command_type = 'disconnect'
                elif 'ECMTCONN' in command_str.upper():
                    command_type = 'conn'
            
            # 解析连接指令
            if command_type == "connect":
                # 匹配: AT+ECMTOPEN=0,"broker",port
                pattern = r'AT\+ECMTOPEN=(\d+),"([^"]+)",(\d+)'
                match = re.match(pattern, command_str)
                if match:
                    client_id = match.group(1)
                    broker = match.group(2)
                    port = int(match.group(3))
                    return {
                        "template": f"AT+ECMTOPEN={client_id},{{host_name}},{{port}}",
                        "original": command_str,
                        "broker": broker,
                        "port": port,
                        "client_id": client_id,
                        "parameters": {
                            "host_name": broker,
                            "port": port
                        }
                    }
                else:
                    # 尝试匹配无引号的格式
                    pattern2 = r'AT\+ECMTOPEN=(\d+),([^,]+),(\d+)'
                    match2 = re.match(pattern2, command_str)
                    if match2:
                        client_id = match2.group(1)
                        broker = match2.group(2).strip('"')
                        port = int(match2.group(3))
                        return {
                            "template": f"AT+ECMTOPEN={client_id},{{host_name}},{{port}}",
                            "original": command_str,
                            "broker": broker,
                            "port": port,
                            "client_id": client_id,
                            "parameters": {
                                "host_name": broker,
                                "port": port
                            }
                        }
            
            # 解析订阅指令
            elif command_type == "subscribe":
                # 匹配: AT+ECMTSUB=client_id,msg_id,"topic",qos
                pattern = r'AT\+ECMTSUB=(\d+),(\d+),"([^"]*)",(\d+)'
                match = re.match(pattern, command_str)
                if match:
                    client_id = match.group(1)
                    msg_id = match.group(2)
                    topic = match.group(3)
                    qos = int(match.group(4))
                    return {
                        "template": f"AT+ECMTSUB={client_id},{msg_id},{{topic}},{{qos}}",
                        "original": command_str,
                        "topic": topic,
                        "qos": qos,
                        "client_id": client_id,
                        "msg_id": msg_id,
                        "parameters": {
                            "topic": topic,
                            "qos": qos
                        }
                    }
                else:
                    # 尝试匹配无引号的格式
                    pattern2 = r'AT\+ECMTSUB=(\d+),(\d+),([^,]+),(\d+)'
                    match2 = re.match(pattern2, command_str)
                    if match2:
                        client_id = match2.group(1)
                        msg_id = match2.group(2)
                        topic = match2.group(3).strip('"')
                        qos = int(match2.group(4))
                        return {
                            "template": f"AT+ECMTSUB={client_id},{msg_id},{{topic}},{{qos}}",
                            "original": command_str,
                            "topic": topic,
                            "qos": qos,
                            "client_id": client_id,
                            "msg_id": msg_id,
                            "parameters": {
                                "topic": topic,
                                "qos": qos
                            }
                        }
            
            # 解析发布指令
            elif command_type == "publish":
                # 匹配: AT+ECMTPUB=client_id,msg_id,topic_qos,retain,"topic","message"
                pattern = r'AT\+ECMTPUB=(\d+),(\d+),(\d+),(\d+),"([^"]+)","([^"]*)"'
                match = re.match(pattern, command_str)
                if match:
                    client_id = match.group(1)
                    msg_id = match.group(2)
                    topic_qos = int(match.group(3))
                    retain = int(match.group(4))
                    topic = match.group(5)
                    message = match.group(6)
                    return {
                        "template": f"AT+ECMTPUB={client_id},{msg_id},{topic_qos},{retain},{{topic}},{{json}}",
                        "original": command_str,
                        "topic": topic,
                        "json": message,
                        "client_id": client_id,
                        "msg_id": msg_id,
                        "topic_qos": topic_qos,
                        "retain": retain,
                        "parameters": {
                            "topic": topic,
                            "json": message,
                            "qos": topic_qos
                        }
                    }
                else:
                    # 尝试匹配无引号的格式
                    pattern2 = r'AT\+ECMTPUB=(\d+),(\d+),(\d+),(\d+),([^,]+),(.+)' 
                    match2 = re.match(pattern2, command_str)
                    if match2:
                        client_id = match2.group(1)
                        msg_id = match2.group(2)
                        topic_qos = int(match2.group(3))
                        retain = int(match2.group(4))
                        topic = match2.group(5).strip('"')
                        message = match2.group(6).strip('"')
                        return {
                            "template": f"AT+ECMTPUB={client_id},{msg_id},{topic_qos},{retain},{{topic}},{{json}}",
                            "original": command_str,
                            "topic": topic,
                            "json": message,
                            "client_id": client_id,
                            "msg_id": msg_id,
                            "topic_qos": topic_qos,
                            "retain": retain,
                            "parameters": {
                                "topic": topic,
                                "json": message,
                                "qos": topic_qos
                            }
                        }
            
            # 解析断开指令
            elif command_type == "disconnect":
                # 匹配: AT+ECMTDISC=client_id 或 AT+ECMTCLOSE=client_id
                pattern = r'AT\+(?:ECMTDISC|ECMTCLOSE)=(\d+)'
                match = re.match(pattern, command_str)
                if match:
                    client_id = match.group(1)
                    # 根据原始命令决定返回哪个模板
                    if 'ECMTDISC' in command_str.upper():
                        template = f"AT+ECMTDISC={client_id}"
                    else:
                        template = f"AT+ECMTCLOSE={client_id}"
                    return {
                        "template": template,
                        "original": command_str,
                        "client_id": client_id,
                        "parameters": {
                            "client_id": client_id
                        }
                    }
            
            # 解析认证连接指令
            elif command_type == "conn" or "ECMTCONN" in command_str.upper():
                # 尝试匹配完整格式: AT+ECMTCONN=client_id,"client_id_value","username","password"
                pattern_full_quoted = r'AT\+ECMTCONN=(\d+),"([^"]+)","([^"]+)","([^"]+)"'
                match = re.match(pattern_full_quoted, command_str)
                if match:
                    client_id = match.group(1)
                    client_id_value = match.group(2)
                    username = match.group(3)
                    password = match.group(4)
                    return {
                        "template": f"AT+ECMTCONN={client_id},{{client_id}},{{username}},{{password}}",
                        "original": command_str,
                        "client_id": client_id,
                        "client_id_value": client_id_value,
                        "username": username,
                        "password": password,
                        "parameters": {
                            "client_id": client_id_value,
                            "username": username,
                            "password": password
                        }
                    }
                else:
                    # 尝试匹配无引号的完整格式: AT+ECMTCONN=client_id,client_id_value,username,password
                    pattern_full_unquoted = r'AT\+ECMTCONN=(\d+),([^,]+),([^,]+),([^,]+)'
                    match2 = re.match(pattern_full_unquoted, command_str)
                    if match2:
                        client_id = match2.group(1)
                        client_id_value = match2.group(2).strip('"')
                        username = match2.group(3).strip('"')
                        password = match2.group(4).strip('"')
                        return {
                            "template": f"AT+ECMTCONN={client_id},{{client_id}},{{username}},{{password}}",
                            "original": command_str,
                            "client_id": client_id,
                            "client_id_value": client_id_value,
                            "username": username,
                            "password": password,
                            "parameters": {
                                "client_id": client_id_value,
                                "username": username,
                                "password": password
                            }
                        }
                    else:
                        # 尝试匹配只有client_id和client_id_value的格式(带引号): AT+ECMTCONN=client_id,"client_id_value"
                        pattern_two_quoted = r'AT\+ECMTCONN=(\d+),"([^"]+)"'
                        match3 = re.match(pattern_two_quoted, command_str)
                        if match3:
                            client_id = match3.group(1)
                            client_id_value = match3.group(2)
                            return {
                                "template": f"AT+ECMTCONN={client_id},{{client_id}},{{username}},{{password}}",
                                "original": command_str,
                                "client_id": client_id,
                                "client_id_value": client_id_value,
                                "username": "",
                                "password": "",
                                "parameters": {
                                    "client_id": client_id_value,
                                    "username": "",
                                    "password": ""
                                }
                            }
                        else:
                            # 尝试匹配只有client_id和client_id_value的格式(无引号): AT+ECMTCONN=client_id,client_id_value
                            pattern_two_unquoted = r'AT\+ECMTCONN=(\d+),([^,]+)'
                            match4 = re.match(pattern_two_unquoted, command_str)
                            if match4:
                                client_id = match4.group(1)
                                client_id_value = match4.group(2).strip('"')
                                return {
                                    "template": f"AT+ECMTCONN={client_id},{{client_id}},{{username}},{{password}}",
                                    "original": command_str,
                                    "client_id": client_id,
                                    "client_id_value": client_id_value,
                                    "username": "",
                                    "password": "",
                                    "parameters": {
                                        "client_id": client_id_value,
                                        "username": "",
                                        "password": ""
                                    }
                                }
                            else:
                                # 尝试匹配只有client_id的格式: AT+ECMTCONN=client_id
                                pattern_only_clientid = r'AT\+ECMTCONN=(\d+)'
                                match5 = re.match(pattern_only_clientid, command_str)
                                if match5:
                                    client_id = match5.group(1)
                                    return {
                                        "template": f"AT+ECMTCONN={client_id},{{client_id}},{{username}},{{password}}",
                                        "original": command_str,
                                        "client_id": client_id,
                                        "client_id_value": "",
                                        "username": "",
                                        "password": "",
                                        "parameters": {
                                            "client_id": "",
                                            "username": "",
                                            "password": ""
                                        }
                                    }
            
            return None
            
        except Exception as e:
            print(f"❌ 指令解析失败: {e}")
            return None
    
    def extract_template_format(self, command_str, command_type=None):
        """专门用于提取标准模板格式的辅助方法
        
        Args:
            command_str (str): 实际的AT指令字符串
            command_type (str, optional): 指令类型
            
        Returns:
            dict: 包含模板格式的信息
        """
        parsed = self.parse_mqtt_command(command_str, command_type)
        if parsed:
            return {
                "template": parsed.get("template", ""),
                "parameters": parsed.get("parameters", {}),
                "original": parsed.get("original", command_str),
                "type": command_type
            }
        return None